<template>
  <div class="operation-log-page art-full-height">
    <!-- 搜索栏 -->
    <div class="search-bar mb-4">
      <el-form ref="searchFormRef" :model="searchForm" :inline="true" label-width="auto">
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="searchDateRange"
            type="daterange"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            class="search-item"
          />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input 
            v-model="searchForm.logUserName" 
            placeholder="请输入用户名" 
            clearable 
            class="search-item"
          />
        </el-form-item>
        <el-form-item label="IP地址">
          <el-input 
            v-model="searchForm.logIp" 
            placeholder="请输入IP地址" 
            clearable 
            class="search-item"
          />
        </el-form-item>
        <el-form-item label="操作模块">
          <el-input 
            v-model="searchForm.logModule" 
            placeholder="请输入操作模块" 
            clearable 
            class="search-item"
          />
        </el-form-item>
        <el-form-item label="操作结果">
          <el-select 
            v-model="searchForm.logSuccessFlag" 
            placeholder="请选择操作结果" 
            clearable
            class="search-item"
          >
            <el-option label="成功" :value="2"></el-option>
            <el-option label="失败" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <ElCard class="art-table-card" shadow="never">
      <!-- 表格头部 -->
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
      </ArtTableHeader>

      <!-- 表格 -->
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      >
      </ArtTable>
    </ElCard>

    <!-- 操作日志详情弹窗 -->
    <OperationLogSearchDialog 
      v-model="detailDialogVisible"
      title="操作日志详情"
      :data="detailData"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, h, onMounted } from 'vue'
import { useTable } from '@/composables/useTable'
import { apiLogOperationPageDataUsingPost, apiLogOperationGetDataUsingPost } from '@/api/apIcaozuorizhi'
import type { ApiLogOperationBoApiLogOperationPageData, ApiLogOperationBoApiLogOperationGetData, RApiLogOperation, RPageDataVoApiLogOperation } from '@/api/types'
import OperationLogSearchDialog from './module/operation-log-search-dialog.vue'
import { DictTag } from '@/components/core/dics/index.vue'
import { View } from '@element-plus/icons-vue'
import { ElPopover } from 'element-plus'

defineOptions({ name: 'OperationLog' })

// 搜索表单
const searchForm = reactive({
  logUserName: '',
  logIp: '',
  logModule: '',
  logExecuteTimeBegin: '',
  logExecuteTimeEnd: '',
  logSuccessFlag: undefined as number | undefined
})

const searchDateRange = ref<[string, string]>(['', ''])

// 详情弹窗
const detailDialogVisible = ref(false)
const detailData = ref<any>({})

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  if (!datetime) return ''
  
  // 处理 "20251029160020" 格式
  if (datetime.length === 14 && /^\d{14}$/.test(datetime)) {
    const year = datetime.substring(0, 4)
    const month = datetime.substring(4, 6)
    const day = datetime.substring(6, 8)
    const hour = datetime.substring(8, 10)
    const minute = datetime.substring(10, 12)
    const second = datetime.substring(12, 14)
    
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`
  }
  
  // 处理标准日期格式
  const date = new Date(datetime)
  if (isNaN(date.getTime())) return datetime
  
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 监听日期范围变化
watch(searchDateRange, (newVal) => {
  if (newVal && newVal.length === 2) {
    searchForm.logExecuteTimeBegin = newVal[0]
    searchForm.logExecuteTimeEnd = newVal[1]
  } else {
    searchForm.logExecuteTimeBegin = ''
    searchForm.logExecuteTimeEnd = ''
  }
})

// 表格配置
const {
  columns,
  columnChecks,
  data,
  loading,
  pagination,
  getData,
  searchParams,
  resetSearchParams,
  handleSizeChange,
  handleCurrentChange,
  refreshData
} = useTable({
  core: {
    apiFn: apiLogOperationPageDataUsingPost,
    apiParams: {
      body: {
        logModule: '',
        logUserName: '',
        logIp: '',
        logSuccessFlag: undefined,
        logExecuteTimeBegin: '',
        logExecuteTimeEnd: '',
        current: 1,
        size: 10
      } as ApiLogOperationBoApiLogOperationPageData
    },
    columnsFactory: () => [
      { type: 'index', width: 60, label: '序号' },
      { prop: 'logUserName', label: '姓名', minWidth: 100 },
      { 
        prop: 'logExecuteTime', 
        label: '时间', 
        minWidth: 160, 
        formatter: (row) => formatDateTime(row.logExecuteTime) 
      },
      { prop: 'logModule', label: '操作模块', minWidth: 110 },
      { prop: 'logContent', label: '操作功能', minWidth: 140 },
      { 
        prop: 'logIp', 
        label: 'IP', 
        minWidth: 130, 
        visible: window.innerWidth >= 768 
      },
      { 
        prop: 'logRequestParam', 
        label: '入参', 
        minWidth: 180,
        formatter: (row) => {
          let paramContent = '';
          if (row.logRequestParam) {
            // 检查是否为有效的JSON字符串
            if (typeof row.logRequestParam === 'string') {
              try {
                // 尝试解析JSON
                const parsed = JSON.parse(row.logRequestParam);
                paramContent = JSON.stringify(parsed, null, 2);
              } catch (e) {
                // 如果解析失败，直接使用原始值
                paramContent = row.logRequestParam;
              }
            } else {
              // 如果不是字符串，直接转换为字符串
              paramContent = String(row.logRequestParam);
            }
          }
          
          return h(ElPopover, {
            placement: 'top-start',
            title: '入参详情',
            width: 400,
            trigger: 'hover'
          }, {
            reference: () => h('div', {
              class: 'param-cell',
              style: 'display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; cursor: pointer;'
            }, paramContent || ''),
            default: () => h('pre', {
              style: 'margin: 0; padding: 8px; max-height: 300px; overflow: auto; white-space: pre-wrap; background: #f5f5f5; border-radius: 4px;'
            }, paramContent)
          })
        }
      },
      { 
        prop: 'logResponseParam', 
        label: '出参', 
        minWidth: 180,
        formatter: (row) => {
          let paramContent = '';
          if (row.logResponseParam) {
            // 检查是否为有效的JSON字符串
            if (typeof row.logResponseParam === 'string') {
              try {
                // 尝试解析JSON
                const parsed = JSON.parse(row.logResponseParam);
                paramContent = JSON.stringify(parsed, null, 2);
              } catch (e) {
                // 如果解析失败，直接使用原始值
                paramContent = row.logResponseParam;
              }
            } else {
              // 如果不是字符串，直接转换为字符串
              paramContent = String(row.logResponseParam);
            }
          }
          
          return h(ElPopover, {
            placement: 'top-start',
            title: '出参详情',
            width: 400,
            trigger: 'hover'
          }, {
            reference: () => h('div', {
              class: 'param-cell',
              style: 'display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; cursor: pointer;'
            }, paramContent || ''),
            default: () => h('pre', {
              style: 'margin: 0; padding: 8px; max-height: 300px; overflow: auto; white-space: pre-wrap; background: #f5f5f5; border-radius: 4px;'
            }, paramContent)
          })
        }
      },
      { 
        prop: 'logSuccessFlag', 
        label: '是否成功', 
        width: 90,
        formatter: (row) => h(DictTag, {
          dictType: '1',
          value: row.logSuccessFlag,
          fallbackText: row.logSuccessFlag === 2 ? '成功' : (row.logSuccessFlag === 1 ? '失败' : '')
        })
      },
      {
        prop: 'operation',
        label: '详情',
        width: 100,
        fixed: 'right',
        formatter: (row) => h(
          'el-button',
          {
            type: 'primary',
            link: true,
            onClick: () => showDetail(row.id),
            title: '查看详情',
            style: {
              backgroundColor: '#f5f7fa',
              border: 'none',
              padding: '4px 8px',
              borderRadius: '4px'
            }
          },
          h(View, { 
            style: { 
              width: '1em', 
              height: '1em', 
              verticalAlign: 'middle',
              color: '#666' 
            } 
          })
        )
      }
    ]
  },
  hooks: {
    onSuccess: (tableData) => {},
    onError: (error) => {}
  }
})

// 查询
const handleSearch = () => {
  searchParams.body.logUserName = searchForm.logUserName || ''
  searchParams.body.logModule = searchForm.logModule || ''
  searchParams.body.logIp = searchForm.logIp || ''
  searchParams.body.logExecuteTimeBegin = searchForm.logExecuteTimeBegin || ''
  searchParams.body.logExecuteTimeEnd = searchForm.logExecuteTimeEnd || ''
  
  if (searchForm.logSuccessFlag !== undefined && searchForm.logSuccessFlag !== null) {
    searchParams.body.logSuccessFlag = Number(searchForm.logSuccessFlag)
  } else {
    searchParams.body.logSuccessFlag = undefined
  }
  
  searchParams.body.current = 1
  searchParams.body.size = 10
  
  getData()
}

// 重置
const handleReset = () => {
  searchForm.logUserName = ''
  searchForm.logModule = ''
  searchForm.logIp = ''
  searchForm.logExecuteTimeBegin = ''
  searchForm.logExecuteTimeEnd = ''
  searchForm.logSuccessFlag = undefined
  searchDateRange.value = ['', '']
  
  resetSearchParams()
  searchParams.body.logSuccessFlag = undefined
  searchParams.body.current = 1
  searchParams.body.size = 10
  
  getData()
}

// 显示详情
const showDetail = async (id: number | string) => {
  const numericId = Number(id)
  if (isNaN(numericId)) {
    return
  }

  try {
    const res = await apiLogOperationGetDataUsingPost({
      body: {
        id: numericId
      } as ApiLogOperationBoApiLogOperationGetData
    })

    if (res) {
      detailData.value = res.data || res
      detailDialogVisible.value = true
    }
  } catch (error) {
    // 异常处理
  }
}

// 初始化数据
onMounted(() => {
  getData()
})
</script>

<style scoped lang="scss">
.operation-log-page {
  .search-bar {
    background-color: var(--el-bg-color-overlay);
    padding: 18px 18px 0;
    border-radius: 4px;
    
    :deep(.el-form-item) {
      margin-right: 16px;
      margin-bottom: 16px;
    }
    
    :deep(.el-form-item__label) {
      font-weight: 500;
      color: var(--el-text-color-regular);
    }
    
    .search-item {
      width: 220px;
    }
  }
  
  :deep(.param-cell) {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 200px;
  }
  :deep(.art-table) {
  width: 100% !important;
  table-layout: auto !important;
  }

}
</style>